#!-*- encoding:utf8 -*-
from django.template import Template, Context, RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib.auth.decorators import user_passes_test, login_required
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger
from django.db.models import Q

from newosmp.monitor.models import Monitor
from newosmp.alert.models import AlertReceive, Alert, AlertBing
from newosmp.host.models import Host, Product, IDC
from newosmp.report.models import Report, ReportReceive
from newosmp.users.models import UserProfile, Authority
from newosmp.strategy.models import Strategy, Tpl
from newosmp.group.models import Group 
from newosmp import settings
from newosmp.util import commom
from newosmp.define import *

import urlparse, urllib
import csv, sys
import MySQLdb
import datetime, time
import hashlib
import math
import json


@login_required
def index(request):
    """
    列出所有监控，并且实现分页操作
    """
    page = int(request.GET.get('page', '1'))
    monitor = Monitor.objects.all()
    for m in monitor:
        ab = AlertBing.objects.get(mid=m.id)
        m.stra = ab.sid.name
        m.group = ab.gid.name 
        
    num = settings.PAGE
    count = monitor.count()
    (monitor, page_list, page_num) = commom.pagination(monitor, page, num)

    (page_up, page_down) = commom.getPage(page, page_num) #上下页
    
    for m in monitor:
        if m.status == 'T':
            m.status = "正常"
        else:
            m.status = "异常"
#        ab = AlertBing.objects.get(mid = Monitor.objects.get(id = m.id))
#        print ab
#        m.s = ab.sid.name
#        m.g = ab.gid.name
#        print m.s, m.g

    #树
    auth_pids = request.session['auth_pids']
    
    tree = ""
    mtree = commom.creatree(-1, tree, '', '/monitor/sub?hid=', auth_pids=auth_pids)
    
    request.session['mtree'] = mtree
    
    return render_to_response("monitor.html", locals())


@login_required
def error(request):
    """
    列出所有监控，并且实现分页操作
    """
    monitor = Monitor.objects.filter(hid=Host.objects.get(id=id), status=0)

    for m in monitor:
        m.available = "异常"
        continue
    return render_to_response("monitor.html", locals())



@login_required
def add(request):
    """
    添加监控，添加完成以后，通知后台daemon程序，同时发出邮件
    """
    #根据请求方式判断操作
    if request.method == 'POST':
        errors = []
        messages = []
        
        #验证通过 - 进行数据持久化操作 首先插入数据主表
        #自动生成tablename,减少选择
        name = request.POST.get(u'name')
        tablename = "data_" + hashlib.md5(name.encode('utf-8')).hexdigest()[:16]
        tpl = request.POST.get('tpl')
        
        stra = Strategy.objects.get(id=int(request.POST.get('stra')))
        group = Group.objects.get(id=int(request.POST.get('group')))
        
        m = Monitor.objects.create(
                name=name,
                url=request.POST.get('url'),
                tpl=request.POST.get('tpl'),
                freq=request.POST.get('freq'),
                #默认添加
                open="T",
                status="T",
                table=tablename,
                pid=Product.objects.get(id=request.POST.get('pid')),
                hid=Host.objects.get(id=request.POST.get('host')))
        m.save()
        
        #生成数据表
        ret = commom.createTplTable(tablename, tpl)
        if ret:
            print u"数据表：%s生成成功" % tablename

        #创建报警策略
        alert = AlertBing.objects.create(mid=m, sid=stra, gid=group)
        alert.save()

        #通知daemon端
        noticeDaemon("start", m.id)
        mtree = request.session['mtree']
        return HttpResponseRedirect("/monitor/")
    else:
        #无操作进入时 - 数据初始化
        idc = IDC.objects.all()
        group = Group.objects.all()
        strategy = Strategy.objects.all()
        tpl = TPL_ITEMS.keys()
        mtree = request.session['mtree']
        return render_to_response("monitoradd.html", locals())

def noticeDaemon(do, id):
    #start, stop, reload
    try:
        url = "%s/%s/%d" % (settings.DaemonUrl, do , id)
        print url
        fd = urllib.urlopen(url)
        data = fd.read()
        fd.close()
        return True
    except:
        return False


def edit(request):
    #修改操作
    if request.method == 'POST':
        
        id = int(request.POST.get('id'))
        #修改主表monitor
        m = Monitor.objects.get(id=id)
        m.name = request.POST.get('name')
        m.url = request.POST.get('url')
        m.tpl = request.POST.get('tpl')
        m.freq = request.POST.get('freq')
        m.pid = Product.objects.get(id=request.POST.get('pid', ''))
        m.hid = Host.objects.get(id=request.POST.get('host', ''))
        m.save()
        noticeDaemon("reload", m.id)
        mtree = request.session['mtree']
        return HttpResponseRedirect("/monitor/")
    else:
        #初始化数据

        id = request.GET.get('id', '')
        #进行数据修改的数据初始化
        monitor = Monitor.objects.get(id=id)#.select_related()
        host = Host.objects.get(id=monitor.hid.id)
        ab = AlertBing.objects.get(mid=id)
        strategy = Strategy.objects.all()
        idc = IDC.objects.all()
        group = Group.objects.all()
        tpl = TPL_ITEMS.keys()
        mtree = request.session['mtree']
        return render_to_response("monitoredit.html", locals())


@login_required
def delete(request):
    """
    修改监控，通知通知daemon端和删除监控人
    """
    id = int(request.GET.get('id', ''))
    m = Monitor.objects.get(id=id)
    m.delete()
    noticeDaemon("stop", id)

    return HttpResponseRedirect("/monitor/")

@login_required
def detail(request):
    """
    显示监控图表
    """
    id = request.GET.get('id', '')
    if id:
        monitor = Monitor.objects.get(id=id)
        mname = monitor.name
        tpl = monitor.tpl 
        tpl_items = TPL_ITEMS[tpl]
        mid = id
        
        alert = Alert.objects.select_related(depth=1).filter(mid=id)
        mtree = request.session['mtree']
        return render_to_response("monitordetail.html", locals())

def sub(request):
    page = int(request.GET.get('page', '1'))
    hid = request.GET.get('hid', '')
    if hid:
        monitor = Monitor.objects.filter(hid=hid)
        for m in monitor:
            ab = AlertBing.objects.get(mid=m.id)
            m.stra = ab.sid.name
            m.group = ab.gid.name 
        
        num = settings.PAGE
        count = monitor.count()
        (monitor, page_list, page_num) = commom.pagination(monitor, page, num)
    
        (page_up, page_down) = commom.getPage(page, page_num) #上下页
        
        for m in monitor:
            if m.status == 'T':
                m.status = "正常"
            else:
                m.status = "异常"
        
        mtree = request.session['mtree']
        
        return render_to_response("monitor.html", locals())
    
def search(request):
    key = request.POST.get('key', '')
    mtree = request.session['mtree']
    if key:
        print key
        q = Q()
        q &= Q(url__contains=key) | Q(name__contains=key) | Q(tpl__contains=key)
        monitor = Monitor.objects.filter(q)
        for m in monitor:
            if m.status == 'T':
                m.status = "正常"
            else:
                m.status = "异常"
    else:
        return HttpResponseRedirect('/monitor/')
    return render_to_response("monitor.html", locals())


def time(request):
    """
    显示监控图表
    """
    start = request.POST.get('start', '')
    end = request.POST.get('end', '')
    start = time.strptime(start, "%Y-%m-%d")
    end = time.strptime(end, "%Y-%m-%d")
    frm = time.mktime(start)
    to = time.mktime(end)
#    print start, "___________", end
#    print frm, "___________", to
    id = request.GET.get('id', '')
    if id:
        monitor = Monitor.objects.get(id=id)
        mname = monitor.name
        tpl = monitor.tpl 
        tpl_items_bytime = TPL_ITEMS[tpl]
        mid = id
        
        alert = Alert.objects.select_related(depth=1).filter(mid=id)
        mtree = request.session['mtree']
        return render_to_response("monitordetail.html", locals())
    
    
    
@login_required
def status(request):
    """
    ajax处理监控开启和关闭
    """
    id = request.GET.get('id', '')
    if id:
        action = request.GET.get('do', '')
        
        if action == "stop":
            open = 'F'
        if action == "start":
            open = 'T' 

        #修改数据库中的状态 
        m = Monitor.objects.get(id=id) 
        m.open = open
        #重置监控状态
        if action == 'start':
            m.status = 'T'
        m.save() 
        noticeDaemon(action, int(id))

    return HttpResponseRedirect("/monitor/")


#多级联动HTML生成
def get(request):
    case = request.GET.get('category')
    html = ""
    if case == 'product':
        html = "<option selected>%s</option>\n" % (u"请选择产品线")
        idc = request.GET.get('idc')
        request.session['idc'] = idc
        host = Host.objects.filter(idc=idc)
        plist = []
        for h in host:
            plist.append(h.pid.id)
        plist = {}.fromkeys(plist).keys() #去重复
        for p in plist:
            product = Product.objects.get(id=p)
            html += '<option value=%s>%s</option>\n' % (product.id, product.name)

    if case == 'host':
        product = request.GET.get('product')
        idc = request.session.get('idc')
        host = Host.objects.filter(idc=idc, pid=product)
        host = {}.fromkeys(host).keys() #去重复
        for h in host:
            html += '<option value="%s">%s-%s</option>\n' % (h.id, h.ip, h.name)

    return HttpResponse(html)


def ajaxGetStra(request):
    id = request.GET.get('id', "")
    stra = Strategy.objects.get(id=int(id))
    dct = commom.str2dct(stra.value)
    if(stra.tpl == "host"):
        cpu = dct.get('cpu', "-1|-1").split('|')
        mem = dct.get('mem', "-1|-1").split('|')
        disk = dct.get('disk', "-1|-1").split('|')
        net = dct.get('net', "-1|-1").split('|')
        load = dct.get('load', "-1|-1").split('|')
    elif (stra.tpl == "mysql"):
        connect = dct.get('connect', "-1|-1").split('|')
        key = dct.get('key', "-1|-1").split('|')
    else:
        tpl = dct.get("value", "-1|-1").split('|')
    return render_to_response("ajaxstra.html", locals())

def ajaxGetGroup(request):
    id = request.GET.get('id', "")
    group = Group.objects.get(id=int(id))
    people = User.objects.filter(id__in=group.user.split(','))
    print people
    return render_to_response("ajaxgroup.html", locals())
